

import 'package:erp/Entity/ProductType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/ProductStore.dart';
import 'package:erp/global.dart';

void registerProductTypeEvents(){
  globalBus.subscribe(Events.PRODUCTTYPE_SELECT_REQUEST, (bus, data) async {
    var productTypes = await externalInterface.getProductTypes(AccountStore.signInResult.token);
    ProductStore.productTypes = productTypes;
    globalBus.publish(Events.PRODUCTTYPE_SELECT_SUCCESS, productTypes);
  });

  globalBus.subscribe<ProductType>(Events.PRODUCTTYPE_INSERT_REQUEST, (bus, data) async {
    try {
      var productType = await externalInterface.addProductType(AccountStore.signInResult.token, data);
      ProductStore.productTypes.add(productType);
      globalBus.publish(Events.PRODUCTTYPE_INSERT_SUCCESS, productType);
    }
    catch (exception){
      globalBus.publish(Events.PRODUCTTYPE_INSERT_ERROR, exception);
    }
  });

  globalBus.subscribe<ProductType>(Events.PRODUCTTYPE_UPDATE_REQUEST, (bus, data) async {
    try {
      var productType = await externalInterface.updateProductType(AccountStore.signInResult.token, (data));
      ProductStore.productTypes.firstWhere((item) => item.id == productType.id)
      ..name = productType.name
      ..imgurl = productType.imgurl;

      globalBus.publish(Events.PRODUCTTYPE_UPDATE_SUCCESS, productType);
    }
    catch (exception){
      globalBus.publish(Events.PRODUCTTYPE_UPDATE_ERROR, exception);
    }
  });

  globalBus.subscribe<ProductType>(Events.PRODUCTTYPE_DELETE_REQUEST, (bus, data) async {
    try {
      var type = await externalInterface.deleteProductType(AccountStore.signInResult.token, data);
      ProductStore.productTypes.removeWhere((item) => item.id == type.id);
      globalBus.publish(Events.PRODUCTTYPE_DELETE_SUCCESS, type);
    }
    catch (exception){
      globalBus.publish(Events.PRODUCTTYPE_DELETE_ERROR, exception);
    }
  });

  globalBus.subscribe<ProductType>(Events.PRODUCTTYPE_UPDATE_SUCCESS, (bus, data){
    ProductStore.products.where((product) => product.typeId == data.id).forEach((product){
      product.typeName = data.name;
    });
    globalBus.publish(Events.PRODUCT_DATA_SELECT_SUCCESS, ProductStore.products);
  });
}

